/**
Copyright 2022 ShenZhen Xiaoniu New Energy Inc. All Rights Reserved.
Author: saico@mosf.cn
**/
import {
  SQSClient,
  SendMessageCommand
} from '@aws-sdk/client-sqs';
import {
  IoTDataPlaneClient,
  PublishCommand
} from '@aws-sdk/client-iot-data-plane';
import {
  IoTClient,
  DescribeThingCommand,
  UpdateThingCommand
} from '@aws-sdk/client-iot';
import config from './config.mjs';
import moment from 'moment-timezone';

const iotCONFIG = {region:process.env.AWS_REGION};
const sqsclient = new SQSClient(iotCONFIG);
const iotclient = new IoTClient(iotCONFIG);
const iotdataclient = new IoTDataPlaneClient(iotCONFIG);

/***********************************************************************************************/

export const mainHandler = async (event, context) => {
    let msgbody = event.Records[0].body;
    let bodyjson = JSON.parse(msgbody);
    let msgtype = bodyjson.msgtype;
    console.log(msgbody);
    console.time('xntask');
    
    if (msgtype==0) {
        let mac = bodyjson.mac;
        let prepotpassed= 10000;  //seconds
        let connected = 1;
        let chargerid = 0;
        let nowtm = moment(new Date().getTime()).tz(process.env.Time_Zone).format(config.SF);
        let thingtypename = '';
        try {
          let iotdata = await iotclient.send(new DescribeThingCommand({thingName:mac}));
          let prepot = moment(iotdata.attributes.pot, config.SF).toDate().getTime();
          connected = Number(iotdata.attributes.connected);
          chargerid = Number(iotdata.attributes.chargerid);
          let nowseconds = moment(moment().tz(process.env.Time_Zone).format(config.SF),config.SF).toDate().getTime();
          prepotpassed = nowseconds - prepot;
          thingtypename = iotdata.thingTypeName;
          console.log('nowTM(tz):'+nowtm+',pot:'+iotdata.attributes.pot+',passed:'+prepotpassed+',thingtypename:'+thingtypename+',cfg.thintype:'+process.env.Default_ThingType);
        } catch (err) {
          console.error(err);
        }
        // charger id = 1,2,3 means OTA update, 1=preup,2=uping,3=verify
        if ( prepotpassed > 60000 && connected > 0 && ( chargerid == 0 || chargerid > 100 ) ) {
          let updatethingParams = {
            thingName: mac,
            attributePayload: {
              attributes: {
                'offtime':nowtm,
                'onltime':'0'
              },
              merge: true
            }
          };
          try {
            await iotclient.send(new UpdateThingCommand(updatethingParams));
          } catch (err) {
            console.error(err);
          }
          let msgbody = {
            msgtype: 1,
            mac:mac
          };
          let arnarr = context.invokedFunctionArn.split(':');
          let SQSURL = config.SQSURLTEMPLATE.replace(/REGION/,arnarr[3]).replace(/ACCOUNTID/,arnarr[4]);
          let qeparams = {
            DelaySeconds: 30,
            MessageBody:JSON.stringify(msgbody),
            QueueUrl: SQSURL
          };
          await sqsclient.send(new SendMessageCommand(qeparams));
        }
    } else if (msgtype==1) {
      let mac = bodyjson.mac;
      let outjson = {'olreq':1};
      let pubparam = {
        topic: config.MQTTWORK+mac,
        payload: Buffer.from(JSON.stringify(outjson)),
        qos: 1
      };
      try {
        await iotdataclient.send(new PublishCommand(pubparam));
      } catch (err) {
        console.error(err);
      }
    } else if (msgtype==2) {
    }
    console.timeEnd('xntask');
};
